# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

from scrapy import signals
from tutorial.cogik_setting import *
import json


class CogikSpiderGenericPipeline(object):

    def __init__(self):
        self.files = {}
        self.checkDups = {}
        self.entries = 0

    @classmethod
    def from_crawler(cls, crawler):
        pipeline = cls()
        crawler.signals.connect(pipeline.spider_opened, signals.spider_opened)
        crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
        return pipeline

    def spider_opened(self, spider):
        fd = open(OUTPUT_ROOT + '/' + spider.name, 'w')
        self.files[spider] = fd

    def spider_closed(self, spider):
        fd = self.files.pop(spider)
        fd.close()
        spider.logger.info('Spider closed:[%s] crawled %d entries' % (
            spider.name, self.entries))

    def process_item(self, item, spider):
        fd = self.files[spider]
        if item['label'] not in self.checkDups:
            self.checkDups[item['label']] = item['item_id']
            self.entries += 1
            fd.write(json.dumps(item))
            # attrjson = json.dumps(item['attr'])
            # brandjson = json.dumps(item['brand'])
            # # attrjson = str(item['attr'])
            # if 'brand' in item:
            #     brandjson = str(item['brand'])
            #     fd.write(item['label'] + '\t' + item['item_id'] + '\t' + attrjson + brandjson + '\n')
            # else:
            #     fd.write(item['label'] + '\t' + item['item_id'] + '\t' + attrjson + '\n')
        return item
